home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / logging / handlers.pyc (.txt) < prev   
Encoding:
Python Compiled Bytecode  |  2007-04-29  |  30.8 KB  |  1,052 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. """
  5. Additional handlers for the logging package for Python. The core package is
  6. based on PEP 282 and comments thereto in comp.lang.python, and influenced by
  7. Apache's log4j system.
  8.  
  9. Should work under Python versions >= 1.5.2, except that source line
  10. information is not available unless 'sys._getframe()' is.
  11.  
  12. Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
  13.  
  14. To use, simply 'import logging' and log away!
  15. """
  16. import sys
  17. import logging
  18. import socket
  19. import types
  20. import os
  21. import string
  22. import cPickle
  23. import struct
  24. import time
  25. import glob
  26.  
  27. try:
  28.     import codecs
  29. except ImportError:
  30.     codecs = None
  31.  
  32. DEFAULT_TCP_LOGGING_PORT = 9020
  33. DEFAULT_UDP_LOGGING_PORT = 9021
  34. DEFAULT_HTTP_LOGGING_PORT = 9022
  35. DEFAULT_SOAP_LOGGING_PORT = 9023
  36. SYSLOG_UDP_PORT = 514
  37. _MIDNIGHT = 24 * 60 * 60
  38.  
  39. class BaseRotatingHandler(logging.FileHandler):
  40.     '''
  41.     Base class for handlers that rotate log files at a certain point.
  42.     Not meant to be instantiated directly.  Instead, use RotatingFileHandler
  43.     or TimedRotatingFileHandler.
  44.     '''
  45.     
  46.     def __init__(self, filename, mode, encoding = None):
  47.         '''
  48.         Use the specified filename for streamed logging
  49.         '''
  50.         if codecs is None:
  51.             encoding = None
  52.         
  53.         logging.FileHandler.__init__(self, filename, mode, encoding)
  54.         self.mode = mode
  55.         self.encoding = encoding
  56.  
  57.     
  58.     def emit(self, record):
  59.         '''
  60.         Emit a record.
  61.  
  62.         Output the record to the file, catering for rollover as described
  63.         in doRollover().
  64.         '''
  65.         
  66.         try:
  67.             if self.shouldRollover(record):
  68.                 self.doRollover()
  69.             
  70.             logging.FileHandler.emit(self, record)
  71.         except (KeyboardInterrupt, SystemExit):
  72.             raise 
  73.         except:
  74.             self.handleError(record)
  75.  
  76.  
  77.  
  78.  
  79. class RotatingFileHandler(BaseRotatingHandler):
  80.     '''
  81.     Handler for logging to a set of files, which switches from one file
  82.     to the next when the current file reaches a certain size.
  83.     '''
  84.     
  85.     def __init__(self, filename, mode = 'a', maxBytes = 0, backupCount = 0, encoding = None):
  86.         '''
  87.         Open the specified file and use it as the stream for logging.
  88.  
  89.         By default, the file grows indefinitely. You can specify particular
  90.         values of maxBytes and backupCount to allow the file to rollover at
  91.         a predetermined size.
  92.  
  93.         Rollover occurs whenever the current log file is nearly maxBytes in
  94.         length. If backupCount is >= 1, the system will successively create
  95.         new files with the same pathname as the base file, but with extensions
  96.         ".1", ".2" etc. appended to it. For example, with a backupCount of 5
  97.         and a base file name of "app.log", you would get "app.log",
  98.         "app.log.1", "app.log.2", ... through to "app.log.5". The file being
  99.         written to is always "app.log" - when it gets filled up, it is closed
  100.         and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
  101.         exist, then they are renamed to "app.log.2", "app.log.3" etc.
  102.         respectively.
  103.  
  104.         If maxBytes is zero, rollover never occurs.
  105.         '''
  106.         if maxBytes > 0:
  107.             mode = 'a'
  108.         
  109.         BaseRotatingHandler.__init__(self, filename, mode, encoding)
  110.         self.maxBytes = maxBytes
  111.         self.backupCount = backupCount
  112.  
  113.     
  114.     def doRollover(self):
  115.         '''
  116.         Do a rollover, as described in __init__().
  117.         '''
  118.         self.stream.close()
  119.         if self.backupCount > 0:
  120.             for i in range(self.backupCount - 1, 0, -1):
  121.                 sfn = '%s.%d' % (self.baseFilename, i)
  122.                 dfn = '%s.%d' % (self.baseFilename, i + 1)
  123.                 if os.path.exists(sfn):
  124.                     if os.path.exists(dfn):
  125.                         os.remove(dfn)
  126.                     
  127.                     os.rename(sfn, dfn)
  128.                     continue
  129.             
  130.             dfn = self.baseFilename + '.1'
  131.             if os.path.exists(dfn):
  132.                 os.remove(dfn)
  133.             
  134.             os.rename(self.baseFilename, dfn)
  135.         
  136.         if self.encoding:
  137.             self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
  138.         else:
  139.             self.stream = open(self.baseFilename, 'w')
  140.  
  141.     
  142.     def shouldRollover(self, record):
  143.         '''
  144.         Determine if rollover should occur.
  145.  
  146.         Basically, see if the supplied record would cause the file to exceed
  147.         the size limit we have.
  148.         '''
  149.         if self.maxBytes > 0:
  150.             msg = '%s\n' % self.format(record)
  151.             self.stream.seek(0, 2)
  152.             if self.stream.tell() + len(msg) >= self.maxBytes:
  153.                 return 1
  154.             
  155.         
  156.         return 0
  157.  
  158.  
  159.  
  160. class TimedRotatingFileHandler(BaseRotatingHandler):
  161.     '''
  162.     Handler for logging to a file, rotating the log file at certain timed
  163.     intervals.
  164.  
  165.     If backupCount is > 0, when rollover is done, no more than backupCount
  166.     files are kept - the oldest ones are deleted.
  167.     '''
  168.     
  169.     def __init__(self, filename, when = 'h', interval = 1, backupCount = 0, encoding = None):
  170.         BaseRotatingHandler.__init__(self, filename, 'a', encoding)
  171.         self.when = string.upper(when)
  172.         self.backupCount = backupCount
  173.         currentTime = int(time.time())
  174.         if self.when == 'S':
  175.             self.interval = 1
  176.             self.suffix = '%Y-%m-%d_%H-%M-%S'
  177.         elif self.when == 'M':
  178.             self.interval = 60
  179.             self.suffix = '%Y-%m-%d_%H-%M'
  180.         elif self.when == 'H':
  181.             self.interval = 60 * 60
  182.             self.suffix = '%Y-%m-%d_%H'
  183.         elif self.when == 'D' or self.when == 'MIDNIGHT':
  184.             self.interval = 60 * 60 * 24
  185.             self.suffix = '%Y-%m-%d'
  186.         elif self.when.startswith('W'):
  187.             self.interval = 60 * 60 * 24 * 7
  188.             if len(self.when) != 2:
  189.                 raise ValueError('You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s' % self.when)
  190.             
  191.             if self.when[1] < '0' or self.when[1] > '6':
  192.                 raise ValueError('Invalid day specified for weekly rollover: %s' % self.when)
  193.             
  194.             self.dayOfWeek = int(self.when[1])
  195.             self.suffix = '%Y-%m-%d'
  196.         else:
  197.             raise ValueError('Invalid rollover interval specified: %s' % self.when)
  198.         self.interval = self.interval * interval
  199.         self.rolloverAt = currentTime + self.interval
  200.         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  201.             t = time.localtime(currentTime)
  202.             currentHour = t[3]
  203.             currentMinute = t[4]
  204.             currentSecond = t[5]
  205.             r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 + currentSecond)
  206.             self.rolloverAt = currentTime + r
  207.             if when.startswith('W'):
  208.                 day = t[6]
  209.                 if day > self.dayOfWeek:
  210.                     daysToWait = day - self.dayOfWeek - 1
  211.                     self.rolloverAt = self.rolloverAt + daysToWait * 60 * 60 * 24
  212.                 
  213.                 if day < self.dayOfWeek:
  214.                     daysToWait = (6 - self.dayOfWeek) + day
  215.                     self.rolloverAt = self.rolloverAt + daysToWait * 60 * 60 * 24
  216.                 
  217.             
  218.         
  219.  
  220.     
  221.     def shouldRollover(self, record):
  222.         '''
  223.         Determine if rollover should occur
  224.  
  225.         record is not used, as we are just comparing times, but it is needed so
  226.         the method siguratures are the same
  227.         '''
  228.         t = int(time.time())
  229.         if t >= self.rolloverAt:
  230.             return 1
  231.         
  232.         return 0
  233.  
  234.     
  235.     def doRollover(self):
  236.         '''
  237.         do a rollover; in this case, a date/time stamp is appended to the filename
  238.         when the rollover happens.  However, you want the file to be named for the
  239.         start of the interval, not the current time.  If there is a backup count,
  240.         then we have to get a list of matching filenames, sort them and remove
  241.         the one with the oldest suffix.
  242.         '''
  243.         self.stream.close()
  244.         t = self.rolloverAt - self.interval
  245.         timeTuple = time.localtime(t)
  246.         dfn = self.baseFilename + '.' + time.strftime(self.suffix, timeTuple)
  247.         if os.path.exists(dfn):
  248.             os.remove(dfn)
  249.         
  250.         os.rename(self.baseFilename, dfn)
  251.         if self.backupCount > 0:
  252.             s = glob.glob(self.baseFilename + '.20*')
  253.             if len(s) > self.backupCount:
  254.                 s.sort()
  255.                 os.remove(s[0])
  256.             
  257.         
  258.         if self.encoding:
  259.             self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
  260.         else:
  261.             self.stream = open(self.baseFilename, 'w')
  262.         self.rolloverAt = self.rolloverAt + self.interval
  263.  
  264.  
  265.  
  266. class SocketHandler(logging.Handler):
  267.     """
  268.     A handler class which writes logging records, in pickle format, to
  269.     a streaming socket. The socket is kept open across logging calls.
  270.     If the peer resets it, an attempt is made to reconnect on the next call.
  271.     The pickle which is sent is that of the LogRecord's attribute dictionary
  272.     (__dict__), so that the receiver does not need to have the logging module
  273.     installed in order to process the logging event.
  274.  
  275.     To unpickle the record at the receiving end into a LogRecord, use the
  276.     makeLogRecord function.
  277.     """
  278.     
  279.     def __init__(self, host, port):
  280.         """
  281.         Initializes the handler with a specific host address and port.
  282.  
  283.         The attribute 'closeOnError' is set to 1 - which means that if
  284.         a socket error occurs, the socket is silently closed and then
  285.         reopened on the next logging call.
  286.         """
  287.         logging.Handler.__init__(self)
  288.         self.host = host
  289.         self.port = port
  290.         self.sock = None
  291.         self.closeOnError = 0
  292.         self.retryTime = None
  293.         self.retryStart = 1.0
  294.         self.retryMax = 30.0
  295.         self.retryFactor = 2.0
  296.  
  297.     
  298.     def makeSocket(self):
  299.         '''
  300.         A factory method which allows subclasses to define the precise
  301.         type of socket they want.
  302.         '''
  303.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  304.         s.connect((self.host, self.port))
  305.         return s
  306.  
  307.     
  308.     def createSocket(self):
  309.         '''
  310.         Try to create a socket, using an exponential backoff with
  311.         a max retry time. Thanks to Robert Olson for the original patch
  312.         (SF #815911) which has been slightly refactored.
  313.         '''
  314.         now = time.time()
  315.         if self.retryTime is None:
  316.             attempt = 1
  317.         else:
  318.             attempt = now >= self.retryTime
  319.         if attempt:
  320.             
  321.             try:
  322.                 self.sock = self.makeSocket()
  323.                 self.retryTime = None
  324.             if self.retryTime is None:
  325.                 self.retryPeriod = self.retryStart
  326.             else:
  327.                 self.retryPeriod = self.retryPeriod * self.retryFactor
  328.                 if self.retryPeriod > self.retryMax:
  329.                     self.retryPeriod = self.retryMax
  330.                 
  331.  
  332.             self.retryTime = now + self.retryPeriod
  333.         
  334.         attempt
  335.  
  336.     
  337.     def send(self, s):
  338.         '''
  339.         Send a pickled string to the socket.
  340.  
  341.         This function allows for partial sends which can happen when the
  342.         network is busy.
  343.         '''
  344.         if self.sock is None:
  345.             self.createSocket()
  346.         
  347.         if self.sock:
  348.             
  349.             try:
  350.                 if hasattr(self.sock, 'sendall'):
  351.                     self.sock.sendall(s)
  352.                 else:
  353.                     sentsofar = 0
  354.                     left = len(s)
  355.                     while left > 0:
  356.                         sent = self.sock.send(s[sentsofar:])
  357.                         sentsofar = sentsofar + sent
  358.                         left = left - sent
  359.             except socket.error:
  360.                 self.sock.close()
  361.                 self.sock = None
  362.             except:
  363.                 None<EXCEPTION MATCH>socket.error
  364.             
  365.  
  366.         None<EXCEPTION MATCH>socket.error
  367.  
  368.     
  369.     def makePickle(self, record):
  370.         '''
  371.         Pickles the record in binary format with a length prefix, and
  372.         returns it ready for transmission across the socket.
  373.         '''
  374.         ei = record.exc_info
  375.         if ei:
  376.             dummy = self.format(record)
  377.             record.exc_info = None
  378.         
  379.         s = cPickle.dumps(record.__dict__, 1)
  380.         if ei:
  381.             record.exc_info = ei
  382.         
  383.         slen = struct.pack('>L', len(s))
  384.         return slen + s
  385.  
  386.     
  387.     def handleError(self, record):
  388.         '''
  389.         Handle an error during logging.
  390.  
  391.         An error has occurred during logging. Most likely cause -
  392.         connection lost. Close the socket so that we can retry on the
  393.         next event.
  394.         '''
  395.         if self.closeOnError and self.sock:
  396.             self.sock.close()
  397.             self.sock = None
  398.         else:
  399.             logging.Handler.handleError(self, record)
  400.  
  401.     
  402.     def emit(self, record):
  403.         '''
  404.         Emit a record.
  405.  
  406.         Pickles the record and writes it to the socket in binary format.
  407.         If there is an error with the socket, silently drop the packet.
  408.         If there was a problem with the socket, re-establishes the
  409.         socket.
  410.         '''
  411.         
  412.         try:
  413.             s = self.makePickle(record)
  414.             self.send(s)
  415.         except (KeyboardInterrupt, SystemExit):
  416.             raise 
  417.         except:
  418.             self.handleError(record)
  419.  
  420.  
  421.     
  422.     def close(self):
  423.         '''
  424.         Closes the socket.
  425.         '''
  426.         if self.sock:
  427.             self.sock.close()
  428.             self.sock = None
  429.         
  430.         logging.Handler.close(self)
  431.  
  432.  
  433.  
  434. class DatagramHandler(SocketHandler):
  435.     """
  436.     A handler class which writes logging records, in pickle format, to
  437.     a datagram socket.  The pickle which is sent is that of the LogRecord's
  438.     attribute dictionary (__dict__), so that the receiver does not need to
  439.     have the logging module installed in order to process the logging event.
  440.  
  441.     To unpickle the record at the receiving end into a LogRecord, use the
  442.     makeLogRecord function.
  443.  
  444.     """
  445.     
  446.     def __init__(self, host, port):
  447.         '''
  448.         Initializes the handler with a specific host address and port.
  449.         '''
  450.         SocketHandler.__init__(self, host, port)
  451.         self.closeOnError = 0
  452.  
  453.     
  454.     def makeSocket(self):
  455.         '''
  456.         The factory method of SocketHandler is here overridden to create
  457.         a UDP socket (SOCK_DGRAM).
  458.         '''
  459.         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  460.         return s
  461.  
  462.     
  463.     def send(self, s):
  464.         '''
  465.         Send a pickled string to a socket.
  466.  
  467.         This function no longer allows for partial sends which can happen
  468.         when the network is busy - UDP does not guarantee delivery and
  469.         can deliver packets out of sequence.
  470.         '''
  471.         if self.sock is None:
  472.             self.createSocket()
  473.         
  474.         self.sock.sendto(s, (self.host, self.port))
  475.  
  476.  
  477.  
  478. class SysLogHandler(logging.Handler):
  479.     """
  480.     A handler class which sends formatted logging records to a syslog
  481.     server. Based on Sam Rushing's syslog module:
  482.     http://www.nightmare.com/squirl/python-ext/misc/syslog.py
  483.     Contributed by Nicolas Untz (after which minor refactoring changes
  484.     have been made).
  485.     """
  486.     LOG_EMERG = 0
  487.     LOG_ALERT = 1
  488.     LOG_CRIT = 2
  489.     LOG_ERR = 3
  490.     LOG_WARNING = 4
  491.     LOG_NOTICE = 5
  492.     LOG_INFO = 6
  493.     LOG_DEBUG = 7
  494.     LOG_KERN = 0
  495.     LOG_USER = 1
  496.     LOG_MAIL = 2
  497.     LOG_DAEMON = 3
  498.     LOG_AUTH = 4
  499.     LOG_SYSLOG = 5
  500.     LOG_LPR = 6
  501.     LOG_NEWS = 7
  502.     LOG_UUCP = 8
  503.     LOG_CRON = 9
  504.     LOG_AUTHPRIV = 10
  505.     LOG_LOCAL0 = 16
  506.     LOG_LOCAL1 = 17
  507.     LOG_LOCAL2 = 18
  508.     LOG_LOCAL3 = 19
  509.     LOG_LOCAL4 = 20
  510.     LOG_LOCAL5 = 21
  511.     LOG_LOCAL6 = 22
  512.     LOG_LOCAL7 = 23
  513.     priority_names = {
  514.         'alert': LOG_ALERT,
  515.         'crit': LOG_CRIT,
  516.         'critical': LOG_CRIT,
  517.         'debug': LOG_DEBUG,
  518.         'emerg': LOG_EMERG,
  519.         'err': LOG_ERR,
  520.         'error': LOG_ERR,
  521.         'info': LOG_INFO,
  522.         'notice': LOG_NOTICE,
  523.         'panic': LOG_EMERG,
  524.         'warn': LOG_WARNING,
  525.         'warning': LOG_WARNING }
  526.     facility_names = {
  527.         'auth': LOG_AUTH,
  528.         'authpriv': LOG_AUTHPRIV,
  529.         'cron': LOG_CRON,
  530.         'daemon': LOG_DAEMON,
  531.         'kern': LOG_KERN,
  532.         'lpr': LOG_LPR,
  533.         'mail': LOG_MAIL,
  534.         'news': LOG_NEWS,
  535.         'security': LOG_AUTH,
  536.         'syslog': LOG_SYSLOG,
  537.         'user': LOG_USER,
  538.         'uucp': LOG_UUCP,
  539.         'local0': LOG_LOCAL0,
  540.         'local1': LOG_LOCAL1,
  541.         'local2': LOG_LOCAL2,
  542.         'local3': LOG_LOCAL3,
  543.         'local4': LOG_LOCAL4,
  544.         'local5': LOG_LOCAL5,
  545.         'local6': LOG_LOCAL6,
  546.         'local7': LOG_LOCAL7 }
  547.     
  548.     def __init__(self, address = ('localhost', SYSLOG_UDP_PORT), facility = LOG_USER):
  549.         '''
  550.         Initialize a handler.
  551.  
  552.         If address is specified as a string, UNIX socket is used.
  553.         If facility is not specified, LOG_USER is used.
  554.         '''
  555.         logging.Handler.__init__(self)
  556.         self.address = address
  557.         self.facility = facility
  558.         if type(address) == types.StringType:
  559.             self._connect_unixsocket(address)
  560.             self.unixsocket = 1
  561.         else:
  562.             self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  563.             self.unixsocket = 0
  564.         self.formatter = None
  565.  
  566.     
  567.     def _connect_unixsocket(self, address):
  568.         self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  569.         
  570.         try:
  571.             self.socket.connect(address)
  572.         except socket.error:
  573.             self.socket.close()
  574.             self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  575.             self.socket.connect(address)
  576.  
  577.  
  578.     log_format_string = '<%d>%s\x00'
  579.     
  580.     def encodePriority(self, facility, priority):
  581.         '''
  582.         Encode the facility and priority. You can pass in strings or
  583.         integers - if strings are passed, the facility_names and
  584.         priority_names mapping dictionaries are used to convert them to
  585.         integers.
  586.         '''
  587.         if type(facility) == types.StringType:
  588.             facility = self.facility_names[facility]
  589.         
  590.         if type(priority) == types.StringType:
  591.             priority = self.priority_names[priority]
  592.         
  593.         return facility << 3 | priority
  594.  
  595.     
  596.     def close(self):
  597.         '''
  598.         Closes the socket.
  599.         '''
  600.         if self.unixsocket:
  601.             self.socket.close()
  602.         
  603.         logging.Handler.close(self)
  604.  
  605.     
  606.     def emit(self, record):
  607.         '''
  608.         Emit a record.
  609.  
  610.         The record is formatted, and then sent to the syslog server. If
  611.         exception information is present, it is NOT sent to the server.
  612.         '''
  613.         msg = self.format(record)
  614.         msg = self.log_format_string % (self.encodePriority(self.facility, string.lower(record.levelname)), msg)
  615.         
  616.         try:
  617.             if self.unixsocket:
  618.                 
  619.                 try:
  620.                     self.socket.send(msg)
  621.                 except socket.error:
  622.                     self._connect_unixsocket(self.address)
  623.                     self.socket.send(msg)
  624.                 except:
  625.                     None<EXCEPTION MATCH>socket.error
  626.                 
  627.  
  628.             None<EXCEPTION MATCH>socket.error
  629.             self.socket.sendto(msg, self.address)
  630.         except (KeyboardInterrupt, SystemExit):
  631.             raise 
  632.         except:
  633.             self.handleError(record)
  634.  
  635.  
  636.  
  637.  
  638. class SMTPHandler(logging.Handler):
  639.     '''
  640.     A handler class which sends an SMTP email for each logging event.
  641.     '''
  642.     
  643.     def __init__(self, mailhost, fromaddr, toaddrs, subject):
  644.         '''
  645.         Initialize the handler.
  646.  
  647.         Initialize the instance with the from and to addresses and subject
  648.         line of the email. To specify a non-standard SMTP port, use the
  649.         (host, port) tuple format for the mailhost argument.
  650.         '''
  651.         logging.Handler.__init__(self)
  652.         if type(mailhost) == types.TupleType:
  653.             (host, port) = mailhost
  654.             self.mailhost = host
  655.             self.mailport = port
  656.         else:
  657.             self.mailhost = mailhost
  658.             self.mailport = None
  659.         self.fromaddr = fromaddr
  660.         if type(toaddrs) == types.StringType:
  661.             toaddrs = [
  662.                 toaddrs]
  663.         
  664.         self.toaddrs = toaddrs
  665.         self.subject = subject
  666.  
  667.     
  668.     def getSubject(self, record):
  669.         '''
  670.         Determine the subject for the email.
  671.  
  672.         If you want to specify a subject line which is record-dependent,
  673.         override this method.
  674.         '''
  675.         return self.subject
  676.  
  677.     weekdayname = [
  678.         'Mon',
  679.         'Tue',
  680.         'Wed',
  681.         'Thu',
  682.         'Fri',
  683.         'Sat',
  684.         'Sun']
  685.     monthname = [
  686.         None,
  687.         'Jan',
  688.         'Feb',
  689.         'Mar',
  690.         'Apr',
  691.         'May',
  692.         'Jun',
  693.         'Jul',
  694.         'Aug',
  695.         'Sep',
  696.         'Oct',
  697.         'Nov',
  698.         'Dec']
  699.     
  700.     def date_time(self):
  701.         '''
  702.         Return the current date and time formatted for a MIME header.
  703.         Needed for Python 1.5.2 (no email package available)
  704.         '''
  705.         (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(time.time())
  706.         s = '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)
  707.         return s
  708.  
  709.     
  710.     def emit(self, record):
  711.         '''
  712.         Emit a record.
  713.  
  714.         Format the record and send it to the specified addressees.
  715.         '''
  716.         
  717.         try:
  718.             import smtplib
  719.             
  720.             try:
  721.                 formatdate = formatdate
  722.                 import email.Utils
  723.             except:
  724.                 formatdate = self.date_time
  725.  
  726.             port = self.mailport
  727.             if not port:
  728.                 port = smtplib.SMTP_PORT
  729.             
  730.             smtp = smtplib.SMTP(self.mailhost, port)
  731.             msg = self.format(record)
  732.             msg = 'From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s' % (self.fromaddr, string.join(self.toaddrs, ','), self.getSubject(record), formatdate(), msg)
  733.             smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  734.             smtp.quit()
  735.         except (KeyboardInterrupt, SystemExit):
  736.             raise 
  737.         except:
  738.             self.handleError(record)
  739.  
  740.  
  741.  
  742.  
  743. class NTEventLogHandler(logging.Handler):
  744.     '''
  745.     A handler class which sends events to the NT Event Log. Adds a
  746.     registry entry for the specified application name. If no dllname is
  747.     provided, win32service.pyd (which contains some basic message
  748.     placeholders) is used. Note that use of these placeholders will make
  749.     your event logs big, as the entire message source is held in the log.
  750.     If you want slimmer logs, you have to pass in the name of your own DLL
  751.     which contains the message definitions you want to use in the event log.
  752.     '''
  753.     
  754.     def __init__(self, appname, dllname = None, logtype = 'Application'):
  755.         logging.Handler.__init__(self)
  756.         
  757.         try:
  758.             import win32evtlogutil
  759.             import win32evtlog
  760.             self.appname = appname
  761.             self._welu = win32evtlogutil
  762.             if not dllname:
  763.                 dllname = os.path.split(self._welu.__file__)
  764.                 dllname = os.path.split(dllname[0])
  765.                 dllname = os.path.join(dllname[0], 'win32service.pyd')
  766.             
  767.             self.dllname = dllname
  768.             self.logtype = logtype
  769.             self._welu.AddSourceToRegistry(appname, dllname, logtype)
  770.             self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
  771.             self.typemap = {
  772.                 logging.DEBUG: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  773.                 logging.INFO: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  774.                 logging.WARNING: win32evtlog.EVENTLOG_WARNING_TYPE,
  775.                 logging.ERROR: win32evtlog.EVENTLOG_ERROR_TYPE,
  776.                 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE }
  777.         except ImportError:
  778.             print 'The Python Win32 extensions for NT (service, event logging) appear not to be available.'
  779.             self._welu = None
  780.  
  781.  
  782.     
  783.     def getMessageID(self, record):
  784.         '''
  785.         Return the message ID for the event record. If you are using your
  786.         own messages, you could do this by having the msg passed to the
  787.         logger being an ID rather than a formatting string. Then, in here,
  788.         you could use a dictionary lookup to get the message ID. This
  789.         version returns 1, which is the base message ID in win32service.pyd.
  790.         '''
  791.         return 1
  792.  
  793.     
  794.     def getEventCategory(self, record):
  795.         '''
  796.         Return the event category for the record.
  797.  
  798.         Override this if you want to specify your own categories. This version
  799.         returns 0.
  800.         '''
  801.         return 0
  802.  
  803.     
  804.     def getEventType(self, record):
  805.         """
  806.         Return the event type for the record.
  807.  
  808.         Override this if you want to specify your own types. This version does
  809.         a mapping using the handler's typemap attribute, which is set up in
  810.         __init__() to a dictionary which contains mappings for DEBUG, INFO,
  811.         WARNING, ERROR and CRITICAL. If you are using your own levels you will
  812.         either need to override this method or place a suitable dictionary in
  813.         the handler's typemap attribute.
  814.         """
  815.         return self.typemap.get(record.levelno, self.deftype)
  816.  
  817.     
  818.     def emit(self, record):
  819.         '''
  820.         Emit a record.
  821.  
  822.         Determine the message ID, event category and event type. Then
  823.         log the message in the NT event log.
  824.         '''
  825.         if self._welu:
  826.             
  827.             try:
  828.                 id = self.getMessageID(record)
  829.                 cat = self.getEventCategory(record)
  830.                 type = self.getEventType(record)
  831.                 msg = self.format(record)
  832.                 self._welu.ReportEvent(self.appname, id, cat, type, [
  833.                     msg])
  834.             except (KeyboardInterrupt, SystemExit):
  835.                 raise 
  836.             except:
  837.                 None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  838.                 self.handleError(record)
  839.             
  840.  
  841.         None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  842.  
  843.     
  844.     def close(self):
  845.         '''
  846.         Clean up this handler.
  847.  
  848.         You can remove the application name from the registry as a
  849.         source of event log entries. However, if you do this, you will
  850.         not be able to see the events as you intended in the Event Log
  851.         Viewer - it needs to be able to access the registry to get the
  852.         DLL name.
  853.         '''
  854.         logging.Handler.close(self)
  855.  
  856.  
  857.  
  858. class HTTPHandler(logging.Handler):
  859.     '''
  860.     A class which sends records to a Web server, using either GET or
  861.     POST semantics.
  862.     '''
  863.     
  864.     def __init__(self, host, url, method = 'GET'):
  865.         '''
  866.         Initialize the instance with the host, the request URL, and the method
  867.         ("GET" or "POST")
  868.         '''
  869.         logging.Handler.__init__(self)
  870.         method = string.upper(method)
  871.         if method not in [
  872.             'GET',
  873.             'POST']:
  874.             raise ValueError, 'method must be GET or POST'
  875.         
  876.         self.host = host
  877.         self.url = url
  878.         self.method = method
  879.  
  880.     
  881.     def mapLogRecord(self, record):
  882.         '''
  883.         Default implementation of mapping the log record into a dict
  884.         that is sent as the CGI data. Overwrite in your class.
  885.         Contributed by Franz  Glasner.
  886.         '''
  887.         return record.__dict__
  888.  
  889.     
  890.     def emit(self, record):
  891.         '''
  892.         Emit a record.
  893.  
  894.         Send the record to the Web server as an URL-encoded dictionary
  895.         '''
  896.         
  897.         try:
  898.             import httplib
  899.             import urllib
  900.             host = self.host
  901.             h = httplib.HTTP(host)
  902.             url = self.url
  903.             data = urllib.urlencode(self.mapLogRecord(record))
  904.             if self.method == 'GET':
  905.                 if string.find(url, '?') >= 0:
  906.                     sep = '&'
  907.                 else:
  908.                     sep = '?'
  909.                 url = url + '%c%s' % (sep, data)
  910.             
  911.             h.putrequest(self.method, url)
  912.             i = string.find(host, ':')
  913.             if i >= 0:
  914.                 host = host[:i]
  915.             
  916.             h.putheader('Host', host)
  917.             if self.method == 'POST':
  918.                 h.putheader('Content-type', 'application/x-www-form-urlencoded')
  919.                 h.putheader('Content-length', str(len(data)))
  920.             
  921.             h.endheaders()
  922.             if self.method == 'POST':
  923.                 h.send(data)
  924.             
  925.             h.getreply()
  926.         except (KeyboardInterrupt, SystemExit):
  927.             raise 
  928.         except:
  929.             self.handleError(record)
  930.  
  931.  
  932.  
  933.  
  934. class BufferingHandler(logging.Handler):
  935.     """
  936.   A handler class which buffers logging records in memory. Whenever each
  937.   record is added to the buffer, a check is made to see if the buffer should
  938.   be flushed. If it should, then flush() is expected to do what's needed.
  939.     """
  940.     
  941.     def __init__(self, capacity):
  942.         '''
  943.         Initialize the handler with the buffer size.
  944.         '''
  945.         logging.Handler.__init__(self)
  946.         self.capacity = capacity
  947.         self.buffer = []
  948.  
  949.     
  950.     def shouldFlush(self, record):
  951.         '''
  952.         Should the handler flush its buffer?
  953.  
  954.         Returns true if the buffer is up to capacity. This method can be
  955.         overridden to implement custom flushing strategies.
  956.         '''
  957.         return len(self.buffer) >= self.capacity
  958.  
  959.     
  960.     def emit(self, record):
  961.         '''
  962.         Emit a record.
  963.  
  964.         Append the record. If shouldFlush() tells us to, call flush() to process
  965.         the buffer.
  966.         '''
  967.         self.buffer.append(record)
  968.         if self.shouldFlush(record):
  969.             self.flush()
  970.         
  971.  
  972.     
  973.     def flush(self):
  974.         '''
  975.         Override to implement custom flushing behaviour.
  976.  
  977.         This version just zaps the buffer to empty.
  978.         '''
  979.         self.buffer = []
  980.  
  981.     
  982.     def close(self):
  983.         """
  984.         Close the handler.
  985.  
  986.         This version just flushes and chains to the parent class' close().
  987.         """
  988.         self.flush()
  989.         logging.Handler.close(self)
  990.  
  991.  
  992.  
  993. class MemoryHandler(BufferingHandler):
  994.     '''
  995.     A handler class which buffers logging records in memory, periodically
  996.     flushing them to a target handler. Flushing occurs whenever the buffer
  997.     is full, or when an event of a certain severity or greater is seen.
  998.     '''
  999.     
  1000.     def __init__(self, capacity, flushLevel = logging.ERROR, target = None):
  1001.         '''
  1002.         Initialize the handler with the buffer size, the level at which
  1003.         flushing should occur and an optional target.
  1004.  
  1005.         Note that without a target being set either here or via setTarget(),
  1006.         a MemoryHandler is no use to anyone!
  1007.         '''
  1008.         BufferingHandler.__init__(self, capacity)
  1009.         self.flushLevel = flushLevel
  1010.         self.target = target
  1011.  
  1012.     
  1013.     def shouldFlush(self, record):
  1014.         '''
  1015.         Check for buffer full or a record at the flushLevel or higher.
  1016.         '''
  1017.         if not len(self.buffer) >= self.capacity:
  1018.             pass
  1019.         return record.levelno >= self.flushLevel
  1020.  
  1021.     
  1022.     def setTarget(self, target):
  1023.         '''
  1024.         Set the target handler for this handler.
  1025.         '''
  1026.         self.target = target
  1027.  
  1028.     
  1029.     def flush(self):
  1030.         '''
  1031.         For a MemoryHandler, flushing means just sending the buffered
  1032.         records to the target, if there is one. Override if you want
  1033.         different behaviour.
  1034.         '''
  1035.         if self.target:
  1036.             for record in self.buffer:
  1037.                 self.target.handle(record)
  1038.             
  1039.             self.buffer = []
  1040.         
  1041.  
  1042.     
  1043.     def close(self):
  1044.         '''
  1045.         Flush, set the target to None and lose the buffer.
  1046.         '''
  1047.         self.flush()
  1048.         self.target = None
  1049.         BufferingHandler.close(self)
  1050.  
  1051.  
  1052.